import sys
import os
import datetime

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class MaintenanceReporter:
    def __init__(self):
        self.db = Database()
    
    def report_maintenance(self, dormitory_id, issue_description):
        """
        报修宿舍
        
        参数:
            dormitory_id (int): 宿舍ID
            issue_description (str): 问题描述
        
        返回:
            bool: 报修成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not dormitory_id or not issue_description:
                print("错误：宿舍ID和问题描述都必须填写")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查宿舍是否存在
            self.db.cursor.execute(
                "SELECT id, building, room_number FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            dormitory = self.db.cursor.fetchone()
            
            if not dormitory:
                print(f"错误：ID为 {dormitory_id} 的宿舍不存在")
                self.db.close()
                return False
            
            # 获取当前日期
            report_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            
            # 插入维修记录
            self.db.cursor.execute(
                "INSERT INTO maintenance (dormitory_id, issue_description, report_date, status) VALUES (?, ?, ?, ?)",
                (dormitory_id, issue_description, report_date, 'pending')
            )
            self.db.conn.commit()
            
            # 更新宿舍状态为维护中
            self.db.cursor.execute(
                "UPDATE dormitory SET status = 'maintenance' WHERE id = ?",
                (dormitory_id,)
            )
            self.db.conn.commit()
            
            print(f"成功：宿舍 {dormitory[1]}-{dormitory[2]} 的维修申请已提交")
            print(f"报修时间：{report_date}")
            print(f"问题描述：{issue_description}")
            return True
        except Exception as e:
            print(f"错误：报修宿舍时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    reporter = MaintenanceReporter()
    
    print("===== 宿舍报修 =====")
    
    # 查询所有宿舍
    db = Database()
    db.connect()
    db.cursor.execute(
        "SELECT id, building, room_number, status FROM dormitory ORDER BY building, room_number"
    )
    dormitories = db.cursor.fetchall()
    db.close()
    
    if not dormitories:
        print("没有找到任何宿舍信息")
    else:
        print("\n宿舍ID\t宿舍\t\t状态")
        for dorm in dormitories:
            print(f"{dorm[0]}\t{dorm[1]}-{dorm[2]}\t{dorm[3]}")
        
        try:
            dormitory_id = int(input("\n请输入要报修的宿舍ID: "))
            issue_description = input("请输入问题描述: ")
            
            reporter.report_maintenance(dormitory_id, issue_description)
        except ValueError:
            print("错误：宿舍ID必须是数字")